const config = require('../config');
const amqp = require('amqplib');

module.exports = {
    send(queue, msg) {
        amqp.connect(config.mqOpt.host).then(
            conn => conn.createChannel().then(
                channel => channel
                .assertQueue(queue, { durable: true })
                .then(
                    _qok => {
                        channel.sendToQueue(queue, Buffer.from(msg));
                        return channel.close().then(()=> conn.close());
                    }
                )
            )
        ).catch(console.warn)
    }, 

    subscribe(queue, callback) {
        amqp.connect(config.mqOpt.host).then(
            conn => conn.createChannel().then(
                channel => channel
                .assertQueue(queue, { durable: true })
                .then(
                    _qok => {
                        channel.consume(queue, msg => {
                            callback(msg.content.toString());
                            channel.ack(msg);
                        }, { noAck: false})
                    }
                )
            )
        );
    }
};